package hotel.quartz.oversea.job.meituan;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.quartz.UrlMtEnums;
import hotel.base.oversea.utils.Result;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  Meituan Hotel Order Reminder Job
 * </p>
 *
 * @description: Meituan Hotel Order Reminder Job
 * @author: qiuyy
 * @date: 2020-05-26 13:22
 * @version: V1.0
 */
@Slf4j
public class MeituanHotelOrderReminderJob implements BaseJob {
    private String timestamp = "Mhorj"+String.valueOf(System.currentTimeMillis());
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * （不操作暂停定时器，一直跑）
     *   判断是否需要催单，数据来源：保存在redis的waitConfirm订单数据
     *   设置每一分钟跑一次接口
     *
     * @param jobExecutionContext
     */
    @Override
    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("Meituan Hotel Order Reminder Job {} >>>>>>>> 催单定时器执行时间: {}",timestamp, DateUtil.now());// 0/10 0 17 * * ?    */10 * * * * ?

        String host = CommonUrlConstants.MEITUAN_HOST;
        //美团接口，查询出订单表处理中的订单,且订单创建时间 大于等于6分钟小于等于14分钟，催单两次
        String dealingOrderUrl = host+ UrlMtEnums.hotelOrder.QUERY_DEALING_ORDER_FOR_REMINDER.getValue();
        String reminderUrl = host+ UrlMtEnums.hotelOrder.REMINDER.getValue();
        String updateReminderCountUrl = host+ UrlMtEnums.hotelOrder.UPDATE_REMINDER_ORDER.getValue();

        List<String> dealingOrderIds =  requestPageDealingOrder(dealingOrderUrl);

        if(null != dealingOrderIds && dealingOrderIds.size()>0){
            log.info("Meituan Hotel Order Reminder Job {} 存在需催单: size={},dealingOrderIds={}",timestamp,dealingOrderIds.size(), JSON.toJSONString(dealingOrderIds));
            //美团催单接口限制  100次/分钟  10000/天  定时器暂时接口先不做请求限制
            for (String mtOrderId:dealingOrderIds){
                //催单接口
                Result result = requestReminderOrder(reminderUrl,mtOrderId);
                if(null != result){
                    String remark = "";
                    if(result.getCode()!= CommonConstants.SUCCESS){
                        log.info("Meituan Hotel Order Reminder Job {} 催单请求成功，结果失败: {}",timestamp,result.getCode());
                    }
                    remark = DateUtil.now()+" "+(String) result.getMsg();
                    if(null != result.getData()){
                        remark += (String)result.getData();
                    }
                    //催过单，update  催单信息 ，is_reminde  is_reminde_remark
                    requestUpdateRemindCount(remark,mtOrderId,updateReminderCountUrl);
                }
            }
            //redisTemplate.opsForValue().set(MeituanConstants.REDIS_MT_HOTEL_ORDER_WAIT_CONFIRM_WAIT_REMIND,redisMap);
        }

        log.info("Meituan Hotel Order Reminder Job {} >>>>>>>> 催单定时器结束时间: {},{}",timestamp, DateUtil.now());
    }

    private List<String> requestPageDealingOrder(String dealingOrderUrl) {
        log.info("Meituan Hotel Order Reminder Job {} 催单定时器进入方法 分页查询处理中酒店 requestPageDealingOrder",timestamp);
        //发起请求
        Result response = JobRestTemplateUtils.post(dealingOrderUrl,null,restTemplate);
        List<String> dtoIds = null;
        if(response.getCode()== CommonConstants.SUCCESS){
            if(null != response.getData()){
                dtoIds = JSON.parseArray(response.getData().toString(),String.class);
            }
        }else{
            log.info("Meituan Hotel Order Reminder Job {} 催单定时器进入方法 获取待处理的催单 获取失败： {}",timestamp, JSON.toJSONString(response));
        }
        log.info("Meituan Hotel Order Reminder Job {} 催单定时器进入方法 分页查询处理中酒店 dtoIds={},response={}",timestamp,dtoIds, JSON.toJSONString(response));
        return dtoIds;
    }

    /**
     * 请求美团催单接口
     * 美团催单接口限制  100次/分钟  10000/天
     * @param reminderUrl
     * @return
     */
    private Result requestReminderOrder(String reminderUrl, String mtOrderId) {
        log.info("Meituan Hotel Order Reminder Job {} 催单定时器进入方法 requestHotelIdsApi: {}",timestamp,mtOrderId);
        Map map = new HashMap();
        map.put("mtOrderId",mtOrderId);
        Result response = JobRestTemplateUtils.post(reminderUrl, JSON.toJSONString(map),restTemplate);

        log.info("Meituan Hotel Order Reminder Job {} 催单定时器进入方法 requestReminderOrder 响应mtOrderId={},response={}",timestamp,mtOrderId, JSON.toJSONString(response));

        return response;
    }

    /**
     * 催单成功更新催单次数
     */
    private void requestUpdateRemindCount(String remark,String oneId,String updateUrl) {
        Map mapUpdate = new HashMap();
        mapUpdate.put("mtOrderId",oneId);
        mapUpdate.put("isReminderRemark",remark);
        log.info("Meituan Hotel Order Reminder Job {} 进入更新订单的催单次数， requestUpdateRemindCount {}",timestamp, JSON.toJSONString(mapUpdate));
        Result response = JobRestTemplateUtils.post(updateUrl, JSON.toJSONString(mapUpdate),restTemplate);
        if(response.getCode()== CommonConstants.SUCCESS){

        }else{
            log.error("Meituan Hotel Order Reminder Job {} 进入更新订单的催单次数失败: {}",timestamp, JSON.toJSONString(response));
        }
    }


}
